package cn.shafish.nettycommon.codec;

import cn.shafish.nettycommon.util.JacksonUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Netty信息编码器（对server端响应的信息进行编码：也就是粘包处理）
 */
public class InvocationEncoder extends MessageToByteEncoder<Invocation> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    protected void encode(ChannelHandlerContext ctx, Invocation invocation, ByteBuf out) throws Exception {
        // 将 Invocation 转换成 byte[] 数组
        byte[] content = JacksonUtils.toByte(invocation);
        // 在out的头int范围写入响应内容的长度
        out.writeInt(content.length);
        // 写入内容
        out.writeBytes(content);
        logger.info("[encode][连接({}) 编码（发送）了一条消息({})]", ctx.channel().id(), invocation.toString());
    }
}
